package com.example.demo.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * List拆分工具类
 * 常用于拆分数据，执行批处理
 *
 * @author MarioZzz
 * @create 2023-11-15 8:45
 */
public class SpiltListUtils {

    private static final int EVERY_NUM = 10;

    public static <E> List<List<E>> spiltList(List<E> list) {
        //总数据量
        int total = list.size();
        //分组数量
        int group = total % EVERY_NUM == 0 ? total / EVERY_NUM : total / EVERY_NUM + 1;
        //将list进行分块
        return Stream.iterate(0, n -> n + 1).
                limit(group).parallel().
                map(seed -> {
                            List<E> list1 = list.stream().skip(seed * EVERY_NUM).limit(EVERY_NUM).
                                    collect(Collectors.toList());
                            return list1;
                        }
                ).collect(ArrayList::new, ArrayList::add, List::addAll);
    }


    /**
     * 平均拆分list方法.
     *
     * @param source
     * @param n
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n;
        int number = source.size() / n;
        //偏移量InsertConsumer
        int offset = 0;
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }


}
